#!/bin/bash
# 操作系统相关的函数库(ubuntu)
# author    : guyadong
# date      : 2019/08/10
# 导入标志,确保只会被导入一次
native_functions_included=true
# 脚本初始化
[ "$common_init_included" != 'true' ] && . ./common_init.sh

function need_install_list {
    local list=
    need_install_mysql && list="$list mysql-server"
    need_install_redis && list="$list redis-server"
    need_install_nginx && list="$list nginx"
    need_install_java8 && list="$list openjdk-8-jdk"
    need_install_node  && list="$list nodejs"
    echo $list
}
function need_install_build_tools {
    local list=
    jdk8_available || list="$list openjdk-8-jdk"
    node_available || list="$list nodejs"
    git_available  || list="$list git"
    echo $list
}
function prepare_node(){
    
    apt-cache policy | grep -F "https://deb.nodesource.com/node_10.x" 1>/dev/null 2>&1 && return 0
    
    local cmd='curl -sL https://deb.nodesource.com/setup_10.x | bash -'
    if which getenforce 1>/dev/null 2>&1&& [  "$(whoami)"  != 'root ' ]
    then
        echo "下面这条命令需要root 用户执行，请输入root用户密码"
        su root sh -c "$cmd" || exit_on_error
    else
        sudo sh -c "$cmd"
    fi
}

# 安装指定的软件包
# $1 待安装的软件包列表
function install_components {
    [ -z "$1" ] && return 0    
    [[ "$1" == *nodejs* ]]  && prepare_node
    sudo apt-get -y update || exit_on_error
    sudo apt-get -y install $1 || exit_on_error
}
# 卸载指定的软件包
# $1 待卸载的软件包列表
function uninstall_components {
    sudo apt-get -y purge $1 || exit_on_error
    sudo apt-get -y autoremove
}

# 扩展删除方法
function uninstall_dependencies_ext(){
    return 0
}
# 定义脚本中用到的程序名对应的软件包
declare -A BASE_TOOL_PKGS=(\
    [grep]=grep \
    [awk]=mawk \
    [nc]=netcat \
    [curl]=curl \
    [wget]=wget \
    [sed]=sed \
    [dialog]=dialog \
    [zip]=zip \
    [unzip]=unzip \
    [bzip2]=bzip2 \
)

# 判断指定的软件包是否安装,已经安装返回0,否则返回1
# $1 软件包名
function is_installed_pkg(){
    [ -n "$1" ] || return 1
    local found="$(dpkg -l $1 2>&1 | grep -P -e '^\w{2}\s+')"
    [ -n "$found" ] || return 1
    local status="$(echo "$found" | awk '{print $1}')" 
    local ii_status="$(echo "$status" | grep 'ii')"
    [ "$status" = "$ii_status" ]
}

# 安装简体中文支持
function install_chinese_support(){
    local name=language-pack-zh-hans*
    is_installed_pkg $name || install_components $name
}
